package main

import (
	"flag"
	"fmt"
	"net"
	"sync"
	"time"
)

func main() {
	ip := flag.String("ip", "", "scan ip")
	start := flag.Int("start", 0, "port scope start")
	end := flag.Int("end", 0, "port scope end")
	timeout := flag.Int("timeout", 1, "port scope timeout, default 1s")
	flag.Parse()
	filter(*ip, *start, *end, *timeout)
}

func filter(ip string, start int, end int, timeout int) {
	port := 0
	if ip == "" {
		fmt.Printf("%s ip为空\n", ip)
		return
	}
	if timeout <= 0 {
		fmt.Printf("%d 超时时间不能设置为负数或0\n", timeout)
		return
	}
	if start != 0 && end == 0 {
		port = start
		handleScan(ip, start, end, port, timeout)
		return
	}
	if start < end {
        //并行执行，加快速度
		var wg sync.WaitGroup
		for i := start; i < end; i++ {
			wg.Add(1)
			go func(j int) {
				defer wg.Done()
				handleScan(ip, start, end, j, timeout)
			}(i)
		}
		wg.Wait()
	}
}

func handleScan(ip string, start int, end int, port int, timeout int) {
	address := fmt.Sprintf("%s:%d", ip, port)
	_, err := net.DialTimeout("tcp", address, time.Duration(timeout)*time.Second)
	if err == nil {
		fmt.Printf("scan result: %s\tsuccess\n", address)
	} else {
		fmt.Printf("scan result: %s\tbe rejected\n", address)
	}
}
